package com.milhouz.wormdroid.gl.model;

import javax.microedition.khronos.opengles.GL10;

import com.milhouz.wormdroid.gl.factory.BotAnimationFactory;
import com.milhouz.wormdroid.gl.model.anim.Animation;
import com.milhouz.wormdroid.gl.model.anim.TexRect;

/**
 * Wormdroid bot sprite
 */
public class BotGLSprite extends GLSprite {

	/** Team id of the bot */
	private int mTeamId;
	/** Indicate if the bot is selected */
	public boolean isSelectedBot = false;
	/** bot orientation (1=right, 2=left, 3=up) */
	public int botOrientation = 1;
	/** Contain animation texture of the bot */
	private Animation[] botAnims;

	public BotGLSprite(int id, int teamId, int x, int y, int width, int height, int resourceId) {
		super(id, x, y, width, height, false, resourceId);
		mTeamId = teamId;
		botAnims = BotAnimationFactory.getInstance().getMarioAnims();
	}

	@Override
	public void draw(GL10 gl, int zx, int zy, boolean isZoomed, float zoomFactor) {
		gl.glBindTexture(GL10.GL_TEXTURE_2D, getTextureName());
		if (isSelectedBot) {
			animate(gl);
		} else {
			waitAnimate(gl);
		}
		// Draw using verts
		gl.glPushMatrix();
		gl.glLoadIdentity();
		if (isZoomed) {
			gl.glScalef(zoomFactor, zoomFactor, 1.0f);
		}
		gl.glTranslatef(getX() + zx, getY() - zy, Z);
		mGrid.draw(gl, true);
		gl.glPopMatrix();
	}

	private void animate(GL10 gl) {
		TexRect texRect = null;
		for (int i = 0; i < botAnims.length; i++) {
			if (botOrientation == 1 && botAnims[i].mAnimationName.equalsIgnoreCase("STOP_RIGHT")) {
				texRect = botAnims[i].next();
				break;
			}
			if (botOrientation == 2 && botAnims[i].mAnimationName.equalsIgnoreCase("STOP_LEFT")) {
				texRect = botAnims[i].next();
				break;
			}
			if (botOrientation == 3 && botAnims[i].mAnimationName.equalsIgnoreCase("JUMP_RIGHT")) {
				texRect = botAnims[i].next();
				break;
			}
		}
		if (texRect != null)
			mGrid.setTextureGrid(gl, texRect);
	}

	private void waitAnimate(GL10 gl) {
		// TODO a adapter
		if (botOrientation == 1) {
			mGrid.setTextureGrid(gl, botAnims[0].getFirstTexRect());
		} else {
			mGrid.setTextureGrid(gl, botAnims[1].getFirstTexRect());
		}
	}

	// --- BOT MOVES
	public void moveLeft() {
		this.botOrientation = 2;
		this.setX(this.getX() - 2);
	}

	public void moveRight() {
		this.botOrientation = 1;
		this.setX(this.getX() + 2);
	}

	public void jump() {
		this.botOrientation = 3;
		this.setY(this.getY() + 4);
	}

	public int getTeamId() {
		return mTeamId;
	}
}
